package com.innovation.ic.cc.base.service.cc.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.innovation.ic.b1b.framework.util.HttpUtils;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.cc.base.mapper.cc.MyCompanyEnterpriseMapper;
import com.innovation.ic.cc.base.mapper.cc.MyCompanyMapper;
import com.innovation.ic.cc.base.model.cc.Dictionaries;
import com.innovation.ic.cc.base.model.cc.ErpMyCompanyName;
import com.innovation.ic.cc.base.model.cc.MyCompany;
import com.innovation.ic.cc.base.model.cc.MyCompanyEnterprise;
import com.innovation.ic.cc.base.model.cc.UploadFile;
import com.innovation.ic.cc.base.model.cc.User;
import com.innovation.ic.cc.base.pojo.MyCompanyMessagePojo;
import com.innovation.ic.cc.base.pojo.MyCompanyPojo;
import com.innovation.ic.cc.base.pojo.RegisterMyCompanyPojo;
import com.innovation.ic.cc.base.pojo.UploadFileMessagePojo;
import com.innovation.ic.cc.base.pojo.UploadFilePojo;
import com.innovation.ic.cc.base.pojo.constant.Constants;
import com.innovation.ic.cc.base.pojo.constant.handler.RabbitMqConstants;
import com.innovation.ic.cc.base.pojo.enums.AuditStatusEnum;
import com.innovation.ic.cc.base.pojo.enums.CurrencyEnum;
import com.innovation.ic.cc.base.pojo.enums.InvoiceTypeEnum;
import com.innovation.ic.cc.base.pojo.enums.MyCompanyEnterpriseEnum;
import com.innovation.ic.cc.base.pojo.enums.MyCompanyEnum;
import com.innovation.ic.cc.base.pojo.enums.UploadFileEnum;
import com.innovation.ic.cc.base.pojo.variable.ServiceResult;
import com.innovation.ic.cc.base.service.ServiceHelper;
import com.innovation.ic.cc.base.service.cc.DictionariesService;
import com.innovation.ic.cc.base.service.cc.ErpMyCompanyNameService;
import com.innovation.ic.cc.base.service.cc.MyCompanyService;
import com.innovation.ic.cc.base.service.cc.UploadFileService;
import com.innovation.ic.cc.base.vo.ErpMyCompanyNameVo;
import com.innovation.ic.cc.base.vo.FileVo;
import com.innovation.ic.cc.base.vo.MyCompanyAddRelation;
import com.innovation.ic.cc.base.vo.MyCompanyVo;
import com.innovation.ic.cc.base.vo.RelationMyCompanyNameVo;
import com.innovation.ic.cc.base.vo.SearchCompanyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class MyCompanyServiceImpl extends ServiceImpl<MyCompanyMapper, MyCompany> implements MyCompanyService {


    @Resource
    private UploadFileService uploadFileService;

    @Resource
    private ErpMyCompanyNameService erpMyCompanyNameService;


    @Resource
    private MyCompanyEnterpriseMapper myCompanyEnterpriseMapper;

    @Resource
    private MyCompanyMapper myCompanyMapper;

    @Resource
    private DictionariesService dictionariesService;


    @Resource
    private ServiceHelper serviceHelper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult registerCompany(MyCompanyVo myCompanyVo) throws IOException {
        ServiceResult serviceResult = new ServiceResult();

        //校验公司,是否重复添加
        Integer associationExistsCount = myCompanyEnterpriseMapper.checkRegistrationCompany(myCompanyVo);
        if (associationExistsCount > 0) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("该公司已与我方建立关系");
            return serviceResult;
        }
        Integer containCompanyNameCount = myCompanyEnterpriseMapper.containCompanyNameCount(myCompanyVo);
        if (containCompanyNameCount > 0) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("该供应商已开通账号，无法新增");
            return serviceResult;
        }
        //查看erp是否有公司
        Map<String, Object> existsErpParamMap = new HashMap<>();
        existsErpParamMap.put("name", myCompanyVo.getName());
        ErpMyCompanyName existsErpMyCompanyName = erpMyCompanyNameService.findByNameMap(existsErpParamMap);

        //判断当前人是否添加本公司
        if (existsErpMyCompanyName != null && existsErpMyCompanyName.getExternalId().equals(myCompanyVo.getEnterpriseId())) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("无法添加本身供应商");
            return serviceResult;
        }
        if (existsErpMyCompanyName == null) {
            ErpMyCompanyNameVo erpMyCompanyNameVo = new ErpMyCompanyNameVo();
            erpMyCompanyNameVo.setName(myCompanyVo.getName());
            erpMyCompanyNameService.saveOrUpdateErpCompany(erpMyCompanyNameVo);
        }
        //校验公司是否异常情况
        //默认为审核通过
        MyCompany existsMyCompany = myCompanyMapper.findByName(myCompanyVo.getName());
        Integer myCompanyId = null;
        if (existsMyCompany == null) {
            //创建我的公司id
            myCompanyId = this.saveMyCompany(myCompanyVo, existsErpMyCompanyName);
        } else {
            //有直接建立关联
            myCompanyId = existsMyCompany.getId();
        }
        //发送MQ,添加公司并且审核
        //this.sendRegisterCompany(myCompanyVo);
        myCompanyVo.setId(myCompanyId);
        //建立关联
        MyCompanyEnterprise myCompanyEnterprise = new MyCompanyEnterprise();
        myCompanyEnterprise.setEnterpriseId(myCompanyVo.getEnterpriseId());
        myCompanyEnterprise.setState(MyCompanyEnum.TO_BE_REVIEWED.getCode());
        myCompanyEnterprise.setMyCompanyId(myCompanyId);
        myCompanyEnterprise.setCreateId(myCompanyVo.getCreateId());
        myCompanyEnterprise.setCreateDate(new Date());
        myCompanyEnterprise.setMainCompany(MyCompanyEnterpriseEnum.NO_ACCORD_WITH.getCode());
        myCompanyEnterpriseMapper.insert(myCompanyEnterprise);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }


    /**
     * 需要添加我的公司
     *
     * @param myCompanyVo
     * @return
     */
    private Integer saveMyCompany(MyCompanyVo myCompanyVo, ErpMyCompanyName existsErpMyCompanyName) {
        //添加MyCompany表
        MyCompany myCompany = new MyCompany();
        BeanUtils.copyProperties(myCompanyVo, myCompany);
        //默认待审核
        myCompany.setCreateDate(new Date());
        myCompany.setCreateId(myCompanyVo.getCreateId());
        if (existsErpMyCompanyName != null && StringUtils.validateParameter(existsErpMyCompanyName.getExternalId())) {
            myCompany.setEnterpriseId(existsErpMyCompanyName.getExternalId());
        }
        if ("FArea01".equals(myCompanyVo.getCountryRegionId())) {
            myCompany.setCurrency(CurrencyEnum.RMB.getType());
            myCompany.setInvoiceType(InvoiceTypeEnum.VAT_SPECIAL_INVOICE.getType());
            myCompany.setInvoiceTypeName(InvoiceTypeEnum.VAT_SPECIAL_INVOICE.getDesc());
        }
        this.baseMapper.insertRetuenId(myCompany);
        //保存图片
        List<String> pictureIds = myCompanyVo.getPictureIds();
        if (!CollectionUtils.isEmpty(pictureIds)) {
            uploadFileService.updateRelationId(pictureIds, UploadFileEnum.MY_COMPANY, myCompany.getId());
        }
        return myCompany.getId();
    }


    /**
     * 绑定参数关联
     *
     * @param myCompanyAddRelation
     * @return
     */
    private Map<String, Object> bindMyCompanyAddRelation(MyCompanyAddRelation myCompanyAddRelation) {
        Map<String, Object> param = new HashMap<>();
        param.put("ID", myCompanyAddRelation.getId());
        param.put("SubID", myCompanyAddRelation.getSubId());
        param.put("Creator", myCompanyAddRelation.getCreator());
        param.put("Files", myCompanyAddRelation.getFiles());
        return param;
    }


    @Override
    public ServiceResult checkRegistrationCompany(MyCompanyVo myCompanyVo) {
        ServiceResult serviceResult = new ServiceResult<>();
        Integer associationExistsCount = myCompanyEnterpriseMapper.checkRegistrationCompany(myCompanyVo);
        //是否存在于当前公司
        if (associationExistsCount > 0) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("该公司已与我方建立关系");
            return serviceResult;
        }
        Integer containCompanyNameCount = myCompanyEnterpriseMapper.containCompanyNameCount(myCompanyVo);
        if (containCompanyNameCount > 0) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("该供应商已开通账号，无法新增");
            return serviceResult;
        }
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    @Override
    public ServiceResult<PageInfo<MyCompanyPojo>> findByMyCompany(SearchCompanyVo searchCompanyVo) {
        ServiceResult<PageInfo<MyCompanyPojo>> serviceResult = new ServiceResult();
        PageHelper.startPage(searchCompanyVo.getPage(), searchCompanyVo.getPageSize());
        List<MyCompanyPojo> list = this.baseMapper.findByMyCompanyPage(searchCompanyVo);
/*        for (MyCompanyPojo myCompanyPojo : list) {
           if (StringUtils.validateParameter(myCompanyPojo.getName()) && myCompanyPojo.getEnterpriseId().equals(searchCompanyVo.getEnterpriseId())) {
                myCompanyPojo.setMainCompany(MyCompanyEnterpriseEnum.ACCORD_WITH.getCode());
            }
        }*/
        PageInfo<MyCompanyPojo> pageInfo = new PageInfo<>(list);
        serviceResult.setResult(pageInfo);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }


    @Override
    public void updateMyCompanyExternalId(ErpMyCompanyNameVo erpMyCompanyNameVo) {
       /* if (!StringUtils.validateParameter(erpMyCompanyNameVo.getName())) {
            return;
        }
        UpdateWrapper<MyCompany> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("name", erpMyCompanyNameVo.getName());
        updateWrapper.set("enterprise_id", erpMyCompanyNameVo.getID());
        updateWrapper.set("country_region_id", erpMyCompanyNameVo.getDistrict());
        updateWrapper.set("company_type_id", erpMyCompanyNameVo.getSupplierType());
        updateWrapper.set("enterprise_nature_id", erpMyCompanyNameVo.getNature());
        updateWrapper.set("invoic_type_id", erpMyCompanyNameVo.getInvoiceType());
        updateWrapper.set("company_registered_address", erpMyCompanyNameVo.getRegAddress());
        //查询币种
        //判断国别,非国内才需要更新
        if (!"FArea01".equals(erpMyCompanyNameVo.getDistrict())) {
            MyCompanyCurrency myCompanyCurrency = myCompanyCurrencyService.findByEnName(erpMyCompanyNameVo.getCurrency());
            if (myCompanyCurrency != null) {
                updateWrapper.set("currency_id", myCompanyCurrency.getId());
            }
        }

        update(updateWrapper);
        //重新更新缓存
        MyCompany myCompany = this.baseMapper.findByEnterpriseId(erpMyCompanyNameVo.getID());
        if (myCompany == null) {
            return;
        }*/
    }

    @Override
    public MyCompany findByName(String name) {
        return this.baseMapper.findByName(name);
    }


    /**
     * 根据creator_id查找我的公司名称列表
     *
     * @param epId
     * @return
     */
    @Override
    public ServiceResult<List<String>> findByEpId(String epId) {
        ServiceResult<List<String>> serviceResult = new ServiceResult<>();
        List<String> myCompanyNameList = myCompanyMapper.findByEpId(epId);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(myCompanyNameList);
        return serviceResult;
    }

    @Override
    public ServiceResult<MyCompanyPojo> getDetail(Integer id) {
        ServiceResult<MyCompanyPojo> serviceResult = new ServiceResult<>();
        MyCompanyPojo myCompanyPojo = new MyCompanyPojo();
        MyCompany myCompany = this.baseMapper.selectById(id);
        BeanUtils.copyProperties(myCompany, myCompanyPojo);
        //查询文件表
        ServiceResult<List<UploadFile>> relationIdList = uploadFileService.findByRelationId(UploadFileEnum.MY_COMPANY, id.toString());
        List<UploadFile> relationIdListResult = relationIdList.getResult();
        List<UploadFilePojo> uploadFilePojoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(relationIdListResult)) {
            for (UploadFile uploadFile : relationIdListResult) {
                UploadFilePojo uploadFilePojo = new UploadFilePojo();
                BeanUtils.copyProperties(uploadFile, uploadFilePojo);
                uploadFilePojoList.add(uploadFilePojo);
            }
        }
        String companyTypeId = myCompany.getCompanyTypeId();
        if (StringUtils.validateParameter(companyTypeId)) {
            ServiceResult<Dictionaries> dictionariesServiceResult = dictionariesService.findById(companyTypeId);
            if (dictionariesServiceResult != null && dictionariesServiceResult.getResult() != null){
                myCompanyPojo.setCompanyTypeName( dictionariesServiceResult.getResult().getDName());
            }
        }
        String countryRegionId = myCompany.getCountryRegionId();
        if (StringUtils.validateParameter(countryRegionId)) {
            ServiceResult<Dictionaries> dictionariesServiceResult = dictionariesService.findById(countryRegionId);
            if (dictionariesServiceResult != null && dictionariesServiceResult.getResult() != null){
                myCompanyPojo.setCountryRegionName( dictionariesServiceResult.getResult().getDName());
            }
        }
        myCompanyPojo.setFiles(uploadFilePojoList);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(myCompanyPojo);
        return serviceResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult deactivateMyCompany(Integer relationEnterpriseId) throws IOException {
        ServiceResult serviceResult = new ServiceResult();
        if (relationEnterpriseId == null) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("id不能为空");
            return serviceResult;
        }
        MyCompanyEnterprise myCompanyEnterprise = myCompanyEnterpriseMapper.selectById(relationEnterpriseId);
        if (myCompanyEnterprise.getMainCompany().equals(MyCompanyEnterpriseEnum.ACCORD_WITH.getCode())) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("主公司不能删除");
            return serviceResult;
        }
        MyCompany myCompany = this.baseMapper.selectById(myCompanyEnterprise.getMyCompanyId());
        myCompanyEnterpriseMapper.deleteById(relationEnterpriseId);
        this.baseMapper.deleteById(myCompanyEnterprise.getMyCompanyId());
        //发送给erp
        //this.sendDeactivateMyCompanyMessage(myCompanyEnterprise.getEnterpriseId(),myCompany.getEnterpriseId());
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage("停用成功");
        return serviceResult;
    }

    @Override
    public void addUserRelation(User userdata) {
        try{
            if(userdata == null){
                return ;
            }
            if (userdata == null) {
                return;
            }
            //主账号才走逻辑
            if (!StringUtils.isEmpty(userdata.getFatherId())) {
                return;
            }
            String enterpriseId = userdata.getEnterpriseId();
            //查询erp是否包含
            ErpMyCompanyName erpMyCompanyName = erpMyCompanyNameService.findByExternalId(enterpriseId);
            if (erpMyCompanyName == null) {
                log.error("添加主账号和公司关联, addUserRelation erpMyCompanyName 返回为空");
                return;
            }
            //查看id是否已经存在
            MyCompany containMyCompany = this.baseMapper.findByEnterpriseId(enterpriseId);
            Integer myCompanyId = null;
            if (containMyCompany == null) {
                MyCompany myCompany = new MyCompany();
                myCompany.setName(erpMyCompanyName.getName());
                myCompany.setCreateDate(new Date());
                myCompany.setEnterpriseId(erpMyCompanyName.getExternalId());
                myCompany.setCountryRegionId(erpMyCompanyName.getDistrict());
                myCompany.setCompanyTypeId(erpMyCompanyName.getType());
                myCompany.setMainProducts(erpMyCompanyName.getProducts());
                myCompany.setSiteId(userdata.getId());
                if ("FArea01".equals(erpMyCompanyName.getDistrict())) {
                    myCompany.setCurrency(CurrencyEnum.RMB.getType());
                    myCompany.setInvoiceType(InvoiceTypeEnum.VAT_SPECIAL_INVOICE.getType());
                    myCompany.setInvoiceTypeName(InvoiceTypeEnum.VAT_SPECIAL_INVOICE.getDesc());
                }
                this.baseMapper.insertRetuenId(myCompany);
                myCompanyId = myCompany.getId();
            } else {
                myCompanyId = containMyCompany.getId();
            }
            //关联判重
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("my_company_id", myCompanyId);
            paramMap.put("enterprise_id", userdata.getEnterpriseId());
            List<MyCompanyEnterprise> myCompanyEnterprises = myCompanyEnterpriseMapper.selectByMap(paramMap);
            if (!CollectionUtils.isEmpty(myCompanyEnterprises)) {
                return;
            }
            //添加关联
            MyCompanyEnterprise myCompanyEnterprise = new MyCompanyEnterprise();
            myCompanyEnterprise.setMyCompanyId(myCompanyId);
            myCompanyEnterprise.setEnterpriseId(enterpriseId);
            myCompanyEnterprise.setMainCompany(MyCompanyEnterpriseEnum.ACCORD_WITH.getCode());
            myCompanyEnterprise.setState(AuditStatusEnum.APPROVE.getErpStatusCode());
            myCompanyEnterprise.setCreateDate(new Date());
            myCompanyEnterpriseMapper.insert(myCompanyEnterprise);
        }catch (Exception e){
            log.error("监听主账号创建，公司关联异常",e);
        }
    }

    @Override
    public void listenDeleteErpCompany(RelationMyCompanyNameVo relationMyCompanyNameVo) {
        //删除关联关系
        if (!StringUtils.validateParameter(relationMyCompanyNameVo.getID()) || !StringUtils.validateParameter(relationMyCompanyNameVo.getSubID())) {
            return;
        }
        //公司名字加关联id
        MyCompany myCompany = this.baseMapper.findByEnterpriseId(relationMyCompanyNameVo.getSubID());
        if (myCompany == null) {
            return;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("enterprise_id", relationMyCompanyNameVo.getID());
        param.put("my_company_id", myCompany.getId());
        myCompanyEnterpriseMapper.deleteByMap(param);
    }

    @Override
    public void listenAuditErpCompany(RelationMyCompanyNameVo relationMyCompanyNameVo) {
        //找到sc公司表
        MyCompany myCompany = this.baseMapper.findByEnterpriseId(relationMyCompanyNameVo.getSubID());
        if (myCompany == null) {
            return;
        }
        UpdateWrapper<MyCompanyEnterprise> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("my_company_id", myCompany.getId());
        updateWrapper.eq("enterprise_id", relationMyCompanyNameVo.getID());
        updateWrapper.set("state", relationMyCompanyNameVo.getStatus());
        updateWrapper.set("cause", relationMyCompanyNameVo.getSummary());
        myCompanyEnterpriseMapper.update(null, updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void relationMyCompanyNameVo(RelationMyCompanyNameVo relationMyCompanyNameVo) {
        if (!StringUtils.validateParameter(relationMyCompanyNameVo.getID())) {
            return;
        }
        if (!StringUtils.validateParameter(relationMyCompanyNameVo.getSubID())) {
            return;
        }
        //查询已经保存的公司
        ErpMyCompanyName erpMyCompanyName = erpMyCompanyNameService.findByExternalId(relationMyCompanyNameVo.getSubID());
        if (erpMyCompanyName == null) {
            return;
        }
        //校验公司,已经添加,查看是否已经添加公司
        Integer count = this.baseMapper.checkRegistrationCompanyId(relationMyCompanyNameVo);
        if (count > 0) {
            return;
        }
        //查看是否需要添加公司表
        MyCompany containMyCompany = this.baseMapper.findByName(erpMyCompanyName.getName());
        MyCompany myCompany = new MyCompany();
        Integer myCompanyId = null;
        if (containMyCompany == null) {
            myCompany.setName(erpMyCompanyName.getName());
            myCompany.setCountryRegionId(erpMyCompanyName.getDistrict());
            myCompany.setCompanyTypeId(erpMyCompanyName.getType());
            myCompany.setMainProducts(erpMyCompanyName.getProducts());
            myCompany.setEnterpriseId(relationMyCompanyNameVo.getSubID());
            //同时解析json文件
            this.baseMapper.insertRetuenId(myCompany);
            myCompanyId = myCompany.getId();
        }else{
            myCompanyId = containMyCompany.getId();
        }
        relationMyCompanyNameVo.setMyCompanyId(myCompanyId.toString());

        //添加关联表
        MyCompanyEnterprise myCompanyEnterprise = new MyCompanyEnterprise();
        myCompanyEnterprise.setEnterpriseId(relationMyCompanyNameVo.getID());
        myCompanyEnterprise.setState(relationMyCompanyNameVo.getStatus());
        myCompanyEnterprise.setMyCompanyId(myCompanyId);
        myCompanyEnterprise.setCreateDate(new Date());
        myCompanyEnterprise.setCause(relationMyCompanyNameVo.getSummary());
        //默认待审核
        myCompanyEnterprise.setState(MyCompanyEnum.TO_BE_REVIEWED.getCode());
        myCompanyEnterprise.setMainCompany(MyCompanyEnterpriseEnum.NO_ACCORD_WITH.getCode());
        myCompanyEnterpriseMapper.insert(myCompanyEnterprise);


        if (StringUtils.validateParameter(relationMyCompanyNameVo.getFiles())) {
            relationMyCompanyNameVo.setID(myCompanyEnterprise.getId().toString());
            Object filesParse = JSONObject.parse(relationMyCompanyNameVo.getFiles());
            if (filesParse == null) {
                return;
            }
            List<FileVo> list = new ArrayList<>();
            JSONArray jsonArray = (JSONArray) filesParse;
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject dataBean = (JSONObject) jsonArray.get(i);
                FileVo fileVo = new FileVo();
                String fileName = dataBean.getString("FileName");
                String url = dataBean.getString("Url");
                fileVo.setFileName(fileName);
                //下载图片，转换连接
                String downloadPicture = downloadPicture(url, fileName);
                if (!StringUtils.validateParameter(downloadPicture)) {
                    continue;
                }
                fileVo.setUrl(downloadPicture);
                list.add(fileVo);
            }
            uploadFileService.saveRelationMyCompanyBatch(list, relationMyCompanyNameVo);
        }
    }


    /**
     * 发送注册消息
     *
     * @param myCompanyVo
     */
    private void sendRegisterCompany(MyCompanyVo myCompanyVo) throws IOException {
        //组装 RegisterMyCompanyPojo
        RegisterMyCompanyPojo registerMyCompanyPojo = new RegisterMyCompanyPojo();
        //主账号公司id
        registerMyCompanyPojo.setEnterpriseID(myCompanyVo.getEnterpriseId());
        registerMyCompanyPojo.setName(myCompanyVo.getName());
        //国别地区,id
        registerMyCompanyPojo.setDistrict(myCompanyVo.getCountryRegionId());
        registerMyCompanyPojo.setProducts(myCompanyVo.getMainProducts());
        registerMyCompanyPojo.setCreator(myCompanyVo.getCreatorUserName());
        //客户类型
        ServiceResult<Dictionaries> dictionariesServiceResult = dictionariesService.findById(myCompanyVo.getCompanyTypeId());
        if (dictionariesServiceResult != null && dictionariesServiceResult.getResult() != null) {
            registerMyCompanyPojo.setType(dictionariesServiceResult.getResult().getDValue());
        }


        registerMyCompanyPojo.setCreator(myCompanyVo.getCreatorUserName());
        //组装文件
        List<UploadFileMessagePojo> uploadFileMessagePojoList = new ArrayList<>();
        ServiceResult<List<UploadFile>> uploadFileResult = uploadFileService.findByRelationId(UploadFileEnum.MY_COMPANY, myCompanyVo.getId() + "");
        if (uploadFileResult != null && !CollectionUtils.isEmpty(uploadFileResult.getResult())) {
            List<UploadFile> uploadFileList = uploadFileResult.getResult();
            for (UploadFile uploadFile : uploadFileList) {
                UploadFileMessagePojo uploadFileMessagePojo = new UploadFileMessagePojo();
                uploadFileMessagePojo.setFileName(uploadFile.getFileName());
                uploadFileMessagePojo.setUrl(uploadFile.getFullPath());
                uploadFileMessagePojoList.add(uploadFileMessagePojo);
            }
            registerMyCompanyPojo.setFiles(uploadFileMessagePojoList);

        }
        JSONObject json = (JSONObject) JSONObject.toJSON(registerMyCompanyPojo);
        // 包装发送到rabbitmq的消息内容
        JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.CC_ERP_REGISTER_COMPANY);
        log.info("推送给rabbitmq注册我的公司消息,交换机:[{}],队列:[{}] , key:[{}] ,的消息内容为:[{}]  ", RabbitMqConstants.CC_ERP_EXCHANGE, RabbitMqConstants.CC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.CC_ERP_REGISTER_COMPANY, result.toString());
        serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.CC_ERP_EXCHANGE, RabbitMqConstants.CC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.CC_ERP_REGISTER_COMPANY, null, result.toString().getBytes());
    }

    private String downloadPicture(String url, String fileName) {
        if (!StringUtils.validateParameter(url)) {
            return null;
        }
        String finalUrl = url;
        if (!url.startsWith(Constants.HTTPS)) {
            finalUrl = Constants.HTTPS + url;
        }
        //后缀名字
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //生成唯一文件名
        String onlyFileName = IdUtil.simpleUUID() + "." + suffix;
        byte[] bytes = null;
        try {
            bytes = HttpUtils.downloadPicture(finalUrl);
        } catch (IOException e) {
            log.error("下载图片发生错误", e);
            return null;
        }
        //上传文件
        serviceHelper.getSftpChannelManager().upload(serviceHelper.getFileParamConfig().getFileUrl(), bytes, onlyFileName);
        return serviceHelper.getFileParamConfig().getImageExhibitionUrl() + onlyFileName;
    }


    private void sendDeactivateMyCompanyMessage(String id,String enterpriseId) throws IOException {
        MyCompanyMessagePojo myCompanyMessagePojo = new MyCompanyMessagePojo();
        myCompanyMessagePojo.setID(id);
        myCompanyMessagePojo.setSubID(enterpriseId);
        JSONObject json = (JSONObject) JSONObject.toJSON(myCompanyMessagePojo);
        // 包装发送到rabbitmq的消息内容
        JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.CC_ERP_DELETE_COMPANY);
        log.info("推送给 erp rabbitmq删除我的公司关联关系 消息,交换机:[{}],队列:[{}] , key:[{}] ,的消息内容为:[{}]  ", RabbitMqConstants.CC_ERP_EXCHANGE, RabbitMqConstants.CC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.CC_ERP_DELETE_COMPANY, result.toString());
        serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.CC_ERP_EXCHANGE, RabbitMqConstants.CC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.CC_ERP_DELETE_COMPANY, null, result.toString().getBytes());
    }

}